<?php

namespace App\Services;

use App\Category;
use Cache;
class CategoryService
{
    public function getCategoryTree()
    {
        $categories = Cache::remember('categories', 86400, function () {
            return $this->getCategoryTreeByDb();
        });
        return $categories;
    }

    public function getCategoryTreeByDb($parentId = null, $allCategories = null)
    {
        if (is_null($allCategories)) {
            // 从数据库中一次性取出所有类目
            $allCategories = Category::all();
        }

        return $allCategories
            // 从所有类目中挑选出父类目 ID 为 $parentId 的类目
            ->where('category_id', $parentId)
            // 遍历这些类目，并用返回值构建一个新的集合
            ->map(function (Category $category) use ($allCategories) {
                $data = ['id' => $category->id, 'title' => $category->title, 'slug' => $category->slug];
                // 如果当前类目不是父类目，则直接返回
                if ($category->category_id) {
                    return $data;
                }
                // 否则递归调用本方法，将返回值放入 children 字段中
                $data['children'] = $this->getCategoryTreeByDb($category->id, $allCategories);

                return $data;
            });
    }
}
